import * as Express from 'express';

import ModuleLoader from './ModuleLoader';
import * as _ from 'lodash';
import RequestMap from './utils/RequestMap';

import WebServer from './http/WebServer'

import Config from './Config'

class Application {

    _ModuleLoader: ModuleLoader;

    private options: any;

    private _requestMap: RequestMap;

    _WebServer: WebServer;

    constructor() {
        this.options = {};
        this._requestMap = new RequestMap();
    }

    configure(conf: any) {
        let _config = _.cloneDeep(conf);
        //配置处更改 
        Object.assign(Config, _config);
        this.options = _.cloneDeep(Config);
        return this;
    }

    private init() {
        let mod = this.options['module']
        this._ModuleLoader = new ModuleLoader({
            root: mod['root']
        });
    }
    /**
     * 启动服务，服务以插件的方式完成
     */
    startup() {
        //加载插件
        let self = this;

        self.init();

        self._ModuleLoader.loadPlugins(function () {
            //判断是否启动Http WebServer
            let http = self.options['http']
            if (http) {
                let port = http.port || 0;
                if (port == 0) {
                    console.error('expected web port ,but got 0');
                } else {
                    let _server = http.server || null;
                    self.withWebServer(_server, http)
                }
            }

            //判断是否启动WebSocket
            let ws = self.options['ws']
            if (ws) {
                let port = ws.port || 0;
                if (port == 0) {
                    console.error('expected web port ,but got 0');
                } else {

                }
            }

        })
    }

    getRequestMap() {
        return this._requestMap;
    }

    private withWebServer(webServer: Express, httpconfig) {
        this._WebServer = new WebServer(this._ModuleLoader, webServer, httpconfig);
        this._WebServer.start();
    }


}

let _Application = new Application();

export { _Application }